package com.tpo.jnotes.client.layer.model.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import com.tpo.jnotes.client.main.Logging;

public class NHibernateUtil
{
    private static SessionFactory sessionFactory;
    private static Session session;

    static
    {
        try
        {
            Logging.trace( "Hibernate > setting configuration" );
            Configuration h2Config = new Configuration().configure();

            ServiceRegistry serviceRegistry =
                new ServiceRegistryBuilder().applySettings( h2Config.getProperties() ).buildServiceRegistry();
            sessionFactory = h2Config.buildSessionFactory( serviceRegistry );
        }
        catch( ExceptionInInitializerError ex )
        {
            Logging.fatal( ex );
        }
    }

    private static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    }

    public static synchronized Session getSession()
    {
        if( session == null )
        {
            session = getSessionFactory().openSession();
            Logging.info( "Hibernate > new session" );
        }
        return session;
    }

    public static void commit()
    {
        Logging.info( "Hibernate > flush!" );
        session.flush();
    }

    public static void shutdown()
    {
        Logging.trace( "Hibernate > shutdown" );
        getSessionFactory().close();
    }

}
